using System;
using System.Collections;
using System.Html;
using System.Runtime.CompilerServices;
using Actors;
using Canvas.ImageRotate;
using Nsb.Classes;
using Yoshi.Classes;
using jQueryApi;
using Awaiter;

namespace YesPlayLove.Clusters
{
    [IgnoreNamespace]
    public class ProfileCluster : ProfileBase
    {
        private const int MonitorInterval = 7000;
        private static int _timer;
        private readonly Eyes _eyes;

        // ReSharper disable NotAccessedField.Local
        private Truple _alias;
        private Truple _birthday;
        private Truple _email;
        private Truple _height;
        private Truple _name;
        private Truple _physique;
        private Actor _slideShow;
        private Truple _smoke;
        private Truple _emmMessage;
        private Truple _emmComment;
        private Truple _emmLike;
        private Truple _bio;
        // ReSharper restore NotAccessedField.Local

        public ProfileCluster(ProfileCluster cluster)
            : base(cluster)
        {
            ProfileCluster = this;
            _eyes = Eyes.BodyEyes();
        }

        public override ProfileBase Build()
        {
            Element = jQuery.FromHtml("<div class='ProfileCluster TrupleCluster'/>")
                ;

            Initialize();

            _alias = PlayAlias();

            _name = Input("name").SubHtml(".Label", "Your Name");

            _email = Input("email").SubHtml(".Label", "Email (hidden to others)");

            _birthday = Input("birthday").SubHtml(".Label", "Birth date m/d/y");

            _physique = SelectBox("physique")
                .SubHtml(".Label", "Physical appearance")
                .SubOptions("select",
                            new Dictionary(
                                "none", UserTheme.LeaveBlank,
                                "petite", "Petite",
                                "slim", "Slim",
                                "athletic", "Athletic",
                                "average", "Average",
                                "curvy", "Curvy",
                                "handfull", "A hand full"
                                )
                )
                ;

            _height = SelectBox("height")
                .SubHtml(".Label", "Height")
                .SubOptions("select", (Dictionary)jQuery.Extend(new Dictionary("none", UserTheme.LeaveBlank), GenHeightList()))
                ;

            _smoke = SelectBox("smoker")
                .SubHtml(".Label", "Do you smoke?")
                .SubOptions("select",
                            new Dictionary(
                                "never", "No",
                                "occasionally", "Occasionally",
                                "yes", "Yes"
                                )
                )
                ;

            _emmMessage = Checkbox("emmMessage").SubHtml(".Label", "Email me when I receive a message");
            _emmComment = Checkbox("emmComment").SubHtml(".Label", "Email me when I receive a comment");
            _emmLike = Checkbox("emmLike").SubHtml(".Label", "Email me when I receive a like");

            _bio = Textarea("bio").SubHtml(".Label", "About you");

            _slideShow = Viewit("https://docs.google.com/present/embed?id=dcxgm95h_820gm7svsdq&autoStart=true&loop=true&interval=7")
                .AddClass("SlideShow")
                .AppendTo(".PageCluster")
                ;
            _slideShow.Element.Plugin<IRot>().Rotate(7);


            new Await()
                .AddAw(FillDataFromAw, Data.My)
                .AddFn(AttachEvents)
                .AddAw(SlideEmInAw)
                .Commit();

            return this;
        }

        [AlternateSignature]
        private extern void Save();

        private void Save(jQueryEvent e)
        {
            ScoopDataTo(Data.My);
            Data.SaveMyProfileAsync(Await.AsyncAw, PkgBase.ResultRx);
        }

        public void Destroy()
        {
            Window.ClearInterval(_timer);
            _timer = 0;
            _eyes.Destroy();
        }

        private void MonitorLoop()
        {
            //Inform.Trace("{0}.MonitorLoop", GetType().Name);
            Data.UpdatePage();
            if (!Data.Saved())
                Save();
        }

        private void SlideEmInAw(Await awp)
        {
            Await ani = new Await();
            ani.Sleep(500);
            AddSlideTruples(ani);
            ani.Sleep(100);
            ani.AddDl(
                delegate
                {
                    jQueryPosition p = _slideShow.Element.Position();
                    _slideShow.Element.CSS(new Dictionary("top", 0, "left", 0));
                          _slideShow
                              .Element.CSS("visibility", "visible")
                              .Animate(new Dictionary("top", p.Top, "left", p.Left), 400, EffectEasing.Swing, delegate { ani.Done(); });
                      });
            ani.AddDx(delegate { jQuery.Select(".Input", _alias.Element).Focus(); });
            ani.AddDx(
                delegate
                {
                    Window.ClearInterval(_timer);
                    _timer = Window.SetInterval(MonitorLoop, MonitorInterval);
                    MonitorLoop();
                }
                );
            ani.Commit(awp);
        }

        private Dictionary GenHeightList()
        {
            Dictionary d = new Dictionary();

            for (int i = 3; i < 8; i++)
            {
                for (int j = 1; j < 12; j++)
                {
                    d[i + "." + j] = String.Format("{0} {2} {1} {3}", i, j, Local.Foot, (j == 1 ? Local.Inch : Local.Inches));
                }
            }

            return d;
        }

        private void AttachEvents()
        {
            jQuery.Select(".Truple .Input")
                .Live("blur.truple", Save)
                .Bind("change.truple", delegate { Data.Saved(false); })
                .Live("keydown.truple", delegate(jQueryEvent e) { if (Keys.ChangeKey(e)) Data.Saved(false); })
                ;

            TrackFocus(true);
        }

        private void TrackFocus(bool eyes)
        {
            jQuery.Select(".Truple .Input")
                .Live("focus.trupleInput",
                      delegate(jQueryEvent e)
                      {
                          Master.Page.FocusEvent(e);
                          jQuery.FromElement(e.Target).AddClass("Focused");
                          try
                          {
                              GetTruple(e.Target).Element.RemoveClass("Focused");
                          }
                          catch
                          {
                          }
                      }
                )
                .Live("blur.trupleInput",
                      delegate(jQueryEvent e)
                      {
                          Master.Page.FocusEvent(e);
                          jQuery.FromElement(e.Target).RemoveClass("Focused");
                          try
                          {
                              GetTruple(e.Target).Element.RemoveClass("Focused");
                          }
                          catch
                          {
                          }
                      }
                )
                ;

            if (eyes)
            {
                jQuery.Select(".Truple")
                    .Live("focus.truple",
                          delegate(jQueryEvent e)
                          {
                              _eyes.MoveToElement(jQuery.FromElement(e.Target));
                          }
                    )
                    ;
            }
        }

    }
}